﻿using ARNative;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;

namespace NRemedy.MVC.UI
{
    public class MenuController : SessionController
    {
        //handle url like /Menu/Query/WS_IncidentStatus/100000/100001/?sid=&sd=&qu=
        //additional route must be config            
        //routes.MapRoute(
        //    null,
        //    "Menu/Query/{form}/{vid}/{tid}",
        //    new { controller = "Menu", action = "Query" } // Parameter defaults
        //    );
        [JsonExceptionHandler]
        public ActionResult Query(string form, uint vid, uint tid, uint? sid, string sd, string qu, FormCollection collection)
        {
            try
            {
                return QueryInternal(ARUserSession.ARContext, form, vid, tid, sid, sd, qu, collection);
            }
            catch (Exception e)
            {

                throw e;
            }
        }

        [NonAction]
        protected virtual ActionResult QueryInternal(
            ARLoginContext context, string form, uint vid, uint tid, uint? sid, string sd, string qu, FormCollection collection)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            List<uint> fields = new List<uint>();
            fields.Add(vid);
            if (vid != tid)
                fields.Add(tid);

            Dictionary<string, uint> store = new Dictionary<string, uint>();

            //check formcollection
            foreach (var key in collection.AllKeys)
            {
                uint id = Convert.ToUInt32(collection[key]);
                if (!fields.Contains(id))
                    fields.Add(id);
                store[key] = id;
            }

            int total = -1;

            List<ARSortInfo> sorts = null;

            if (sid != null)
            {
                sorts = new List<ARSortInfo>();
                sorts.Add(new ARSortInfo
                {
                    FieldId = sid.Value,
                    Order = sd == "desc" ? SortOrder.SORT_DESCENDING : SortOrder.SORT_ASCENDING
                });
            }

            var entries = context.ServerInstance.GetEntryList(form, qu, fields, 0, null, ref total, sorts);

            //List<MenuDataJsonModel> models = new List<MenuDataJsonModel>();
            JsonBuilder collections = new JsonBuilder(JsonBuilderRoot.Collection);
            List<object> values = new List<object>();

            foreach (var entry in entries)
            {
                JsonBuilder builder = new JsonBuilder();
                bool skip = false;
                foreach (var fvs in entry.FieldValues)
                {
                    if (fvs.FieldId == vid)
                    {
                        builder.MergeProperty("v", fvs.Value);
                        if (!values.Contains(fvs.Value))
                            values.Add(fvs.Value);
                        else
                        {
                            skip = true;
                        }
                    }
                    if (fvs.FieldId == tid)
                        builder.MergeProperty("t", fvs.Value);
                    if (store.Values.Contains(fvs.FieldId))
                    {
                        foreach (var k in store.Keys)
                        {
                            if (store[k] == fvs.FieldId)
                            {
                                builder.MergeProperty(k, fvs.Value.ToString().ToARKeyWordDecoded(this));
                            }
                        }
                    }
                }
                //models.Add(MenuDataJsonModel.Create(entry, vid, tid));
                if (!skip)
                    collections.MergeCollectionObject(builder);
            }

            //return Json(models.Distinct(Equality<MenuDataJsonModel>.CreateComparer(m => m.v)),
            //    JsonRequestBehavior.AllowGet);
            return new RawJsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = collections.ToString() };
        }

    }
}
